define(function (require) {

    var util = require('util');
    var ui = require('ui');
    var $ = require("jquery");
    var angular = require("angular");
    require("pagination");
    require('angular-interceptor');
    require("angular-ui");
    require('global');
    require("/static_public/js/angular_directive/projectTreeSelector");
    require("/ydxs_static/public/js/plugins/filterCombobox");

    var app = angular.module('customerFollowManage', ['ngInterceptor','ngPublicUI','ngUI','projectTreeSelector', 'filterCombobox']);
    app.constant('apibe', '/api/')
        .constant('NEED_TOKEN', 'true')
        .constant('apife', 'index.php?r=ydxs/')
        .factory('url', [
            function () {
                return {
                    //给url添加search字符串
                    addParam: function (url, search) {
                        for (var key in search) {
                            if (search.hasOwnProperty(key) && search[key] != undefined) {
                                var connecter = "&";
                                if (url.indexOf('?') === -1) {
                                    connecter = "?";
                                }
                                url += connecter + key + '=' + encodeURIComponent(search[key]);
                            }
                        }
                        return url;
                    }
                };
            }
        ])
        .factory('http', [
            '$http',
            'url',
            'apibe',
            'apife',
            'NEED_TOKEN',
            function ($http, url, apibe, apife, NEED_TOKEN) {
                var requrl = apibe + apife;
                return {
                    get: function (api, search) {
                        search = angular.extend(search || {}, {rnd: Math.random()})
                        api = url.addParam(requrl + api, search);
                        return $http.get(api, {needToken: NEED_TOKEN});
                    },
                    post: function (api, data, search) {
                        var dataMap = [];
                        for (var key in data) {
                            if (data.hasOwnProperty(key)) {
                                var val = data[key];
                                if (angular.isObject(val)) {
                                    val = JSON.stringify(val);
                                }
                                dataMap.push(key + '=' + encodeURIComponent(val));
                            }
                        }
                        data = dataMap.join('&');
                        search = angular.extend(search || {}, {rnd: Math.random()})
                        api = url.addParam(requrl + api, search);
                        return $http.post(api, data, {
                            headers: {
                                'Content-Type': 'application/x-www-form-urlencoded'
                            },
                            needToken: NEED_TOKEN
                        });
                    }
                };
            }
        ])
        .factory('customerFollowService', [
            'http',
            function (http) {
                var httpClient = {
                    get: function (api, options) {
                        return http.get(api, options.search)
                            .success(function (res) {
                                if (res.retCode == 0) {
                                    return options.success(res);
                                }
                                options.fail && options.fail(res);
                            })
                            .error(function (res) {
                                options.fail && options.fail(res);
                            });
                    },
                    post: function (api, options) {
                        return http.post(api, options.data, options.search)
                            .success(function (res) {
                                if (res.retCode == 0) {
                                    return options.success(res);
                                }
                                options.fail && options.fail(res);
                            })
                            .error(function (res) {
                                options.fail && options.fail(res);
                            });
                    }
                };

                return {
                    getCustomerList: function (options) {
                        return httpClient.get('genjin-mng/get-list', options);
                    },
                    postCustomerList: function (options) {
                        return httpClient.post('genjin-mng/get-list', options);
                    },
                    exportList: function (options) {
                        return httpClient.get('genjin-mng/export', options)
                    },
                    getSalersList: function (options) {
                        return httpClient.get('genjin-mng/get-saler-list', options);
                    },
                    getProjectList: function (options) {
                        return httpClient.get('project/list/', options);
                    }

                }
            }
        ])

    app.controller('CustomFollowController', [
        '$rootScope',
        '$scope',
        'apibe',
        'apife',
        'customerFollowService',
        'url',
        function ($rootScope, $scope, apibe, apife, service,url) {
            $scope.search = {
                fieldList: [{text: '客户姓名', value: 'cst_name'}, {text: '客户电话', value: 'mobile_tel'}],
                searchField: 'cst_name',
                searchText: '',
                consultantList: [],
                consultantField: '',
                pageIndex: 1,
                pageSize: 10,
                startDate: '',
                endDate: ''
            };

            service.getProjectList({
                search:{
                    flag:"0",//
                    jointparent: 1//
                },
                success: function (res) {
                    if (res.retCode == 0) {
                        $scope.projectList = res.data;
                    } else {
                        ui.showErrTip(res.retMsg || res.errMsg || '获取数据失败！');
                    }
                }
            })


            $scope.update = function () {
                var paramsData = $scope.getFilterParams();
                $scope.getList({
                    search: {
                        page_index: $scope.search.pageIndex,
                        page_size: $scope.search.pageSize
                    },
                    data: paramsData,
                    success: function (res) {
                        if (res.retCode == 0) {
                            $scope.customerlist = res.data.list;
                            $scope.total = res.data.total;
                        } else {

                        }
                    },
                    fail: function (res) {
                        //ui.showErrTip(res.retMsg || '获取数据失败！');
                    }
                });
            };

            /**
             * 清空筛选条件
             */
            $scope.clearFilter = function () {
                $scope.search.startDate = null;
                $scope.search.endDate = null;
                $scope.search.pageIndex = 1;
                $scope.search.searchText = '';
                $scope.search.consultantField = '';
                $scope.getList({
                    search: {
                        page_index: $scope.search.pageIndex,
                        page_size: $scope.search.pageSize
                    },
                    data: {
                        proj_id: $scope.curProjectId
                    },
                    success: function (res) {
                        if (res.retCode == 0) {
                            $scope.customerlist = res.data.list
                            $scope.total = res.data.total;
                        }
                    },
                    fail: function (res) {
                        //ui.showErrTip(res.retMsg || '获取数据失败！');
                    }
                });
            };

            /**
             * 获取数据
             * @param options  条件
             */
            $scope.getList = function (options) {
                var searchParams = _.extend(options.search || {}, options.data || {});
                service.getCustomerList({
                    search: searchParams,
                    success: function (res) {
                        if (res.retCode == 0) {
                            $scope.customerlist = res.data.list
                            $scope.total = res.data.total;
                        }
                    },
                    fail: function (res) {
                        //ui.showErrTip(res.retMsg || '获取数据失败！');
                    }
                });
            };

            /**
             * 翻页
             * @param {int} pageIndex
             */
            $scope.getDataPage = function (pageIndex) {
                $scope.search.pageIndex = pageIndex;
                var paramsData = $scope.getFilterParams();
                $scope.getList({
                    search: {
                        page_index: $scope.search.pageIndex,
                        page_size: $scope.search.pageSize
                    },
                    data: paramsData,
                    success: function (res) {
                        if (res.retCode == 0) {
                            $scope.customerlist = res.data.list
                            $scope.total = res.data.total;
                        }
                    },
                    fail: function (res) {
                        //ui.showErrTip(res.retMsg || '获取数据失败！');
                    }
                });
            };

            /**
             * 取得查询参数
             */
            $scope.getFilterParams = function () {
                var ret = {}
                ret.proj_id = $scope.curProjectId;
                if ($scope.search.consultantField) {
                    ret.user_id = $scope.search.consultantField;
                }
                if ($scope.search.startDate) {
                    ret.gj_start_time = $scope.search.startDate;
                }

                if ($scope.search.endDate) {
                    ret.gj_end_time = $scope.search.endDate;
                }

                if ($scope.search.searchText) {
                    ret[$scope.search.searchField] = $scope.search.searchText;
                }
                return ret
            };

            /**
             * 搜索
             */
            $scope.searchData = function () {
                $scope.search.pageIndex = 1;
                var paramsData = _.pick($scope.getFilterParams(), 'proj_id', 'cst_name', 'mobile_tel');
                var searchParams = _.extend({
                    page_index: $scope.search.pageIndex,
                    page_size: $scope.search.pageSize
                }, paramsData);
                $scope.getList({
                    search: searchParams,
                    success: function (res) {
                        if (res.retCode == 0) {
                            $scope.customerlist = res.data.list
                            $scope.total = res.data.total;
                        }
                    },
                    fail: function (res) {
                        //ui.showErrTip(res.retMsg || '获取数据失败！');
                    }
                })
            };

            /**
             * 过滤查询
             */
            $scope.filterData = function () {
                $scope.search.pageIndex = 1;
                var paramsData = $scope.getFilterParams();
                $scope.getList({
                    search: {
                        page_index: $scope.search.pageIndex,
                        page_size: $scope.search.pageSize
                    },
                    data: paramsData,
                    success: function (res) {
                        if (res.retCode == 0) {
                            $scope.customerlist = res.data.list
                            $scope.total = res.data.total;
                        }
                    },
                    fail: function (res) {
                        //ui.showErrTip(res.retMsg || '获取数据失败！');
                    }

                });

            };

            /**
             * 导出
             */
            $scope.exportData = function () {
                var paramsData = $scope.getFilterParams();
                var downloadurl = url.addParam(apibe + apife  + 'genjin-mng/export',paramsData);
                util.download(downloadurl, {});
            };

            $scope.$watch('curProjectId', function () {
                if ($scope.curProjectId) {
                    $scope.update($scope.curProjectId);
                    service.getSalersList({
                        search: {
                            proj_id: $scope.curProjectId
                        },
                        success: function (res) {
                            if (res.retCode == 0) {
                                var dataList = _.map(res.data, function (item) {
                                    item.text = item.user_name + '(' + item.mobile_tel + ')';
                                    return item;
                                });
                                $scope.search.consultantList = dataList;
                            }
                        },
                        fail: function (res) {
                            //ui.showErrTip(res.retMsg || res.errMsg || '获取数据失败！');
                        }
                    });
                }
            });
        }
    ])

    angular.element(document).ready(function () {
        angular.bootstrap(document, ["customerFollowManage"]);
    });
});
